//
//  CreateAdvertisingFormSwiftViewController.swift
//  iModern
//
//  Created by 立雄 王 on 15/6/26.
//  Copyright (c) 2015年 com.starlooking. All rights reserved.
//

import UIKit
import XLForm
import CoreLocation

class CreateArticleFormViewController: FormViewController, CLLocationManagerDelegate
{
    var attachments: NSMutableArray!
    var article        = NSMutableDictionary()
    var articleManager = ArticleManager()

    var locationManager: CLLocationManager = CLLocationManager()
    var geocoder:        CLGeocoder        = CLGeocoder()

    override func viewDidLoad()
    {
        super.viewDidLoad()

        self.navigationItem.title = "发布动态"
        self.getCity()
        self.initBackButton()

        let image  = UIImage(named: "Save-Small.png")
        let button = UIBarButtonItem(image: image?.imageWithRenderingMode(.AlwaysOriginal), style: .Plain, target: self, action: "createArticle:")
        self.navigationItem.rightBarButtonItem = button

        self.initializeForm()
    }

    func initializeForm()
    {
        var form:    XLFormDescriptor
        var section: XLFormSectionDescriptor
        var row:     XLFormRowDescriptor

        form = XLFormDescriptor(title: " ")

        section = XLFormSectionDescriptor.formSectionWithTitle("")
        section.footerTitle = ""
        form.addFormSection(section)


        row = XLFormRowDescriptor(tag: "message", rowType: XLFormRowDescriptorTypeTextView, title: "我要分享")
        row.required = true
        section.addFormRow(row)


        row = XLFormRowDescriptor(tag: "address", rowType: XLFormRowDescriptorTypeText, title: "位置:")
        row.required = true
        section.addFormRow(row)

        self.form = form

    }

    func getCity()
    {
        if !CLLocationManager.locationServicesEnabled()
        {
            print("定位服务当前可能尚未打开，请设置打开！");
            return
        }
        //如果没有授权则请求用户授权
        if CLLocationManager.authorizationStatus() == CLAuthorizationStatus.NotDetermined
        {
            locationManager.requestWhenInUseAuthorization()
        }
        else if CLLocationManager.authorizationStatus() == CLAuthorizationStatus.AuthorizedWhenInUse
        {
            locationManager.delegate = self
            locationManager.desiredAccuracy = kCLLocationAccuracyBest
            locationManager.distanceFilter = 10.0
            //启动跟踪定位
            locationManager.startUpdatingLocation()
        }
    }

    func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
    {
        let thelocations: NSArray    = locations as NSArray
        let location:     CLLocation = thelocations.objectAtIndex(0) as! CLLocation
        //let latitude                 = location.coordinate.latitude
        //let longitude                = location.coordinate.longitude

        //let placemarks: NSArray? = NSArray()
        //var error:      NSError?
        //反地理编码
        geocoder.reverseGeocodeLocation(location, completionHandler: {
            (placemarks, error) -> Void in
            if error == nil && placemarks!.count > 0
            {
                let placemark:  CLPlacemark         = ((placemarks!.first) as CLPlacemark?)!
                let addressRow: XLFormRowDescriptor = self.form.formRowWithTag("address")!
                addressRow.value = "\(placemark.locality)"
                self.tableView .reloadData()
            }
        })
        //如果不需要实时定位，使用完即使关闭定位服务
        self.locationManager.stopUpdatingLocation()
    }

    @IBAction func createArticle(sender: AnyObject)
    {

        let message = self.formValues()["message"] as? String
        if message == nil
        {
            self.alertWarningMessage("请填写分享内容")
            return
        }
        let address = self.formValues()["address"] as? String
        if address == nil
        {
            self.alertWarningMessage("请填写城市")
            return
        }

        self.article["message"] = self.formValues()["message"]
        self.article["address"] = self.formValues()["address"]

        let rs = articleManager.createArticle(self.article as [NSObject:AnyObject])
        if rs == nil
        {
            self.alertNetworkConnectionException()
            return
        }

        if rs!.hasErrors()
        {
            if rs?.errorCode == 3020
            {
                self.alertUserStatusException()
            }
            else
            {
                self.alertErrorMessage(rs!.errorMessage)
            }
        }
        self.view.endEditing(true)
        self.navigationController?.popToRootViewControllerAnimated(true)
    }

    override func didReceiveMemoryWarning()
    {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    /*
    // MARK: - Navigation
    
    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    // Get the new view controller using segue.destinationViewController.
    // Pass the selected object to the new view controller.
    }
    */

}
